<template>
  <view class="login page-bgColor">
    <view class="title">{{ typeStatus === 1 ? "注册" : "登录" }}</view>
    <tui-form ref="form">
      <tui-form-item padding="0" marginBottom="40" marginTop="90">
        <tui-input
          :placeholder="
            typeStatus === 1 ? '请输入用户名' : '请输入用户名/手机号'
          "
          v-model="formData.account"
        >
          <template v-slot:left>
            <span class="icon icon_user"></span>
          </template>
        </tui-input>
      </tui-form-item>
      <tui-form-item padding="0" marginBottom="40">
        <tui-input placeholder="请输入密码" password v-model="formData.pass">
          <template v-slot:left>
            <span class="icon icon_psd"></span>
          </template>
        </tui-input>
      </tui-form-item>
      <tui-form-item padding="0" marginBottom="40" v-show="typeStatus === 1">
        <tui-input placeholder="请输入推荐ID(选填)"  v-model="formData.refereeID">
          <template v-slot:left>
            <span class="icon icon_refer"></span>
          </template>
        </tui-input>
      </tui-form-item>
      <tui-form-item padding="0" marginBottom="40" v-show="typeStatus === 1">
        <tui-input placeholder="请输入手机号" v-model="formData.phone">
          <template v-slot:left>
            <span class="icon icon_phone"></span>
          </template>
        </tui-input>
      </tui-form-item>
      <tui-form-item padding="0" marginBottom="40" v-show="typeStatus === 1">
        <tui-input placeholder="请输入邮箱" v-model="formData.email">
          <template v-slot:left>
            <span class="icon icon_email"></span>
          </template>
        </tui-input>
      </tui-form-item>
      <tui-form-item padding="0" marginBottom="40" v-show="typeStatus === 1">
        <tui-input placeholder="请输入验证码" v-model="formData.verifyCode">
          <template v-slot:left>
            <span class="icon icon_validate"></span>
          </template>
          <template v-slot:right>
            <span
              v-show="seconds <= 0"
              class="text-theme-color"
              @click="getCode"
              >获取验证码</span
            >
            <span v-show="seconds > 0" style="color: #aaa">{{ seconds }}s</span>
          </template>
        </tui-input>
      </tui-form-item>
      <tui-form-item
        padding="0"
        marginBottom="40"
        marginTop="60"
        v-show="typeStatus === 1"
      >
        <tui-form-button radiu="20" @click="submitHandler"
          >注册</tui-form-button
        >
      </tui-form-item>
      <tui-form-item
        padding="0"
        marginBottom="40"
        marginTop="60"
        v-show="typeStatus === 2"
      >
        <tui-form-button radiu="20" @click="submitHandler"
          >登录</tui-form-button
        >
      </tui-form-item>
      <!-- <tui-form-item padding="0" marginBottom="40" marginTop="60"> -->
      <block class="login_bottom">
        <view class="agreement">
          <checkbox
            :checked="checkedAgrement"
            @click="checkedAgrement = !checkedAgrement"
          ></checkbox>
          <tui-text text="用户协议" color="#31D49D"></tui-text>及<tui-text
            text="隐私协议"
            color="#31D49D"
          ></tui-text
          >链接
        </view>
        <!-- <tui-link text="已有账号,去登陆" underline color="#31D49D"> </tui-link> -->
        <view
          v-show="typeStatus === 1"
          class="title"
          style="color: #31d49d; text-decoration: underline; font-size: 28rpx"
          @click="changeStatus(2)"
        >
          已有账号,去登陆</view
        >
        <view
          v-show="typeStatus === 2"
          class="title"
          style="color: #31d49d; text-decoration: underline; font-size: 28rpx"
          @click="changeStatus(1)"
        >
          暂无账号，去注册</view
        >
      </block>
      <!-- </tui-form-item> -->
    </tui-form>
  </view>
</template>

<script>
import "../../common/app.css";
export default {
  data() {
    function checkAccount(value) {
      console.log("value", value);

      function isValidUsername(username) {
        // 定义正则表达式
        const usernameRegex = username.length > 4;
        // 测试并返回结果
        return usernameRegex;
      }
      return isValidUsername(value);

      return true;
    }
    function checkRefereeID(value) {
      function isValidLengthType(value) {
            const regex = /^\d{6}$/; // 匹配恰好 6 个数字
            return regex.test(value); // 返回验证结果
        }
        return isValidLengthType(value)
    }
    
    return {
      seconds: 0,
      timer: null,
      formData: {
        account: "",
        refereeID:'',
        pass: "",
        phone: "",
        email: "",
        verifyCode: "",
      },
      checkedAgrement: false,
      typeStatus: 2, //1：注册页面 2：登录页面
      rules: [
        {
          name: "account",
          rule: ["required"],
          msg: ["请输入账号"],
          // validator: [
          //   {
          //     msg: "账号格式不正确",
          //     method: checkAccount,
          //   },
          // ],
        },
        {
          name: "pass",
          rule: ["required"],
          msg: ["请输入密码"],
        },
        {
          name: "phone",
          rule: ["required", "isMobile"],
          msg: ["请输入手机号", "手机格式不正确"],
        },
        // {
        //   name: "refereeID",
        //        validator: [
        //     {
        //       msg: "请输入正确的推荐人ID",
        //       method: checkRefereeID,
        //     },
        //   ],
        // },
        {
          name: "email",
          rule: ["required", "isEmail"],
          msg: ["请输入邮箱", "邮箱格式不正确"],
        },
        {
          name: "verifyCode",
          rule: ["required"],
          msg: ["请输入验证码"],
        },
      ],
      ruleEamil: [
        {
          name: "email",
          rule: ["required", "isEmail"],
          msg: ["请输入邮箱", "邮箱格式不正确"],
        },
      ],

      rulesLogin: [
        {
          name: "account",
          rule: ["required"],
          msg: ["请输入账号"],
          // validator: [
          //   {
          //     msg: "账号格式不正确",
          //     method: checkAccount,
          //   },
          // ],
        },
        {
          name: "pass",
          rule: ["required"],
          msg: ["请输入密码"],
        },
      ],
    };
  },
  methods: {
    changeStatus(e) {
      this.formData = this.$options.data().formData;
      this.typeStatus = e;
    },

    getCode() {
      this.$refs.form
        .validate(this.formData, this.ruleEamil)
        .then((res) => {
          if (res.isPass) {
            console.log(this.formData);
            console.log("校验通过！");

            this.tui
              .request(
                `/ESOP_Member/index.ashx?Email=${this.formData.email}`,
                "post",
                {
                  m: "MakeAndSendEmailVerifyCode",
                  "Content-Type": "multipart/form-data",
                }
              )
              .then((res) => {
                console.log("res----", res);
                this.tui.toast(res.ReturnMessage);
              })
              .catch((err) => {
                console.log("err", err);
              });

            this.seconds = 60;
            this.timer = setInterval(() => {
              if (this.seconds <= 0) {
                clearInterval(this.timer);
              }
              this.seconds -= 1;
            }, 1000);
          } else {
            console.log(res);
          }
        })
        .catch((errors) => {
          console.log(errors);
        });
    },
    submitHandler() {
      if (!this.checkedAgrement) {
        return this.tui.toast("请勾选用户协议");
      }
      let mapperFun = {
        1: () => {
          this.$refs.form
            .validate(this.formData, this.rules)
            .then((res) => {
              if (res.isPass) {
                console.log(this.formData);
                console.log("校验通过！");
                this.tui
                  .request(
                    `/ESOP_Member/index.ashx?MemberName=${this.formData.account}&ReferrerMemberName=${this.formData.refereeID}&MobileNumber=${this.formData.phone}&Email=${this.formData.email}&Pass=${this.formData.pass}&VerifyCode=${this.formData.verifyCode}`,
                    "post",
                    {
                      m: "register",
                      "Content-Type": "multipart/form-data",
                    }
                  )
                  .then((res) => {
                    console.log("22222", res);
                    this.tui.toast(res.ReturnMessage);
                    if (res.IsSuccess) {
                      this.changeStatus(2);
                    }
                  })
                  .catch((errors) => {
                    console.log(errors);
                  });
              } else {
                console.log(res);
              }
            })
            .catch((errors) => {
              console.log(errors);
            });
        },
        2: () => {
          this.$refs.form
            .validate(this.formData, this.rulesLogin)
            .then((res) => {
              if (res.isPass) {
                console.log(this.formData);
                console.log("校验通过！");
                this.tui
                  .request(
                    `/Login/index.ashx?LoginID=${this.formData.account}&Pass=${this.formData.pass}`,
                    "POST",
                    {
                      m: "login",
                      "Content-Type": "multipart/form-data",
                    }
                  )
                  .then((res) => {
                    console.log("loginRes:", res);
                    this.tui.toast(res.ReturnMessage);
                    console.log("token", res.Data.access_token);
                    if (res.IsSuccess) {
                      uni.setStorageSync(
                        "profile",
                        JSON.stringify({
                          ...res.Data,
                          ...res.DataDic,
                        })
                      );

                      uni.switchTab({
                        url: "/pages/index/index",
                      });
                    }
                  });
              } else {
                console.log(res);
              }
            })
            .catch((errors) => {
              console.log(errors);
            });
        },
      };
      mapperFun[this.typeStatus]();
    },
  },
  onShow() {
    if (uni.getStorageSync("profile")) {
      const profile = JSON.parse(uni.getStorageSync("profile"));
      profile.access_token &&
        uni.switchTab({
          url: "/pages/index/index",
        });
    }
  },
  watch: {
    checkedAgrement: {
      handler(nw, old) {
        console.log("nw:", nw);
      },
      deep: true,
    },
  },
};
</script>

<style>
.login {
  padding: 50rpx 30rpx 0 30rpx;
}

.login_bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: var(--theme-bgColor);
}

.title {
  font-weight: 600;
  font-size: 46rpx;
  color: #1d1d1d;
}

.icon {
  display: inline-block;
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}

.icon_user {
  background: url(@/static/images/login/login_user.png);
  background-size: 100%;
}

.icon_psd {
  background: url(@/static/images/login/login_psd.png);
  background-size: 100%;
}
.icon_refer {
  background: url(@/static/images/login/login_refer.png);
  background-size: 100%;
}

.icon_phone {
  background: url(@/static/images/login/login_phone.png);
  background-size: 100%;
}

.icon_email {
  background: url(@/static/images/login/login_email.png);
  background-size: 100%;
}

.icon_validate {
  background: url(@/static/images/login/login_validate.png);
  background-size: 100%;
}

.agreement {
  color: #c2c2c2;
}
</style>